package com.jumeng.util;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;

@Slf4j
public class WxUtils {

    public static String getReceiveAccessToken(String appid, String appsecret) {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;
        return HttpUtils.get(url);
    }

    /**
     * 返回结果例子
     * {
     * "access_token":"ACCESS_TOKEN",
     * "expires_in":7200,
     * "refresh_token":"REFRESH_TOKEN",
     * "openid":"OPENID",
     * "scope":"SCOPE",
     * "is_snapshotuser": 1,
     * "unionid": "UNIONID"
     * }
     * 如果用户同意授权，页面将跳转至 redirect_uri/?code=CODE&state=STATE。
     * code作为换取access_token的票据，每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期。
     */
    public static void oauth2Authorize(String appid, String redirectUri) {
        // 例https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx807d86fb6b3d4fd2&redirect_uri=http%3A%2F%2Fdevelopers.weixin.qq.com&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + redirectUri + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        String str = HttpUtils.get(url);
        log.error("oauth2Authorize，{}", str);
    }


    /**
     * 获取access_token和openId
     * {
     *   "access_token":"ACCESS_TOKEN",
     *   "expires_in":7200,
     *   "refresh_token":"REFRESH_TOKEN",
     *   "openid":"OPENID",
     *   "scope":"SCOPE",
     *   "is_snapshotuser": 1,
     *   "unionid": "UNIONID"
     * }
     * 返回结果
     *
     * 网页授权接口调用凭证,注意：此access_token与基础支持的access_token不同
     * openid:用户唯一标识，请注意，在未关注公众号时，用户访问公众号的网页，也会产生一个用户和公众号唯一的OpenID
     * unionid: 用户统一标识（针对一个微信开放平台账号下的应用，同一用户的 unionid 是唯一的），只有当scope为"snsapi_userinfo"时返回
     */
    public static String receiveOpenId(String appid, String secret, String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
        return HttpUtils.get(url);
    }

    /**
     * 获取用户基本信息
     * 正常情况下，微信会返回下述JSON数据包给公众号：
     * todo
     * {
     *     "subscribe": 1,
     *     "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M",
     *     "language": "zh_CN",
     *     "subscribe_time": 1382694957,
     *     "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL",
     *     "remark": "",
     *     "groupid": 0,
     *     "tagid_list":[128,2],
     *     "subscribe_scene": "ADD_SCENE_QR_CODE",
     *     "qr_scene": 98765,
     *     "qr_scene_str": ""
     * }
     */
    public static void receiveWxUser(String accessToken, String openId) {
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid= " + openId + "&lang=zh_CN";
    }
}
